package mqtt

import (
	"context"
	"fmt"
	"gitee.com/injoyai/goutil/string/logs/v1"
	"github.com/DrmagicE/gmqtt"
	_ "github.com/DrmagicE/gmqtt/persistence"
	"github.com/DrmagicE/gmqtt/pkg/packets"
	"github.com/DrmagicE/gmqtt/server"
	_ "github.com/DrmagicE/gmqtt/topicalias/fifo"
	"log"
	"net"
)

type Server struct {
	server.Server
}

func NewServer(port int) error {
	ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
	if err != nil {
		return err
	}
	srv := server.New(server.WithTCPListener(ln))
	if err := srv.Init(server.WithHook(server.Hooks{
		OnConnected: func(ctx context.Context, client server.Client) {
			logs.Debugf("新的客户端连接:%s", client.ClientOptions().ClientID)
			// add subscription for a client when it is connected
			srv.SubscriptionService().Subscribe(client.ClientOptions().ClientID, &gmqtt.Subscription{
				TopicFilter: client.ClientOptions().ClientID,
				QoS:         packets.Qos0,
			})
		},
		OnMsgArrived: func(ctx context.Context, client server.Client, req *server.MsgArrivedRequest) error {
			logs.Debugf("发布主题:%s,消息内容:%s", req.Message.Topic, string(req.Message.Payload))
			return nil
		},
	})); err != nil {
		return err
	}
	log.Printf("[信息] 开启MQTT服务(%d)成功...\n", port)
	if err := srv.Run(); err != nil {
		return err
	}
	return nil
}
